package com.sunedai.tiger.service.system;

import cn.hutool.core.util.StrUtil;
import com.sunedai.tiger.common.enumeration.EnumDictType;
import com.sunedai.tiger.common.enumeration.EnumOrdNoType;
import com.sunedai.tiger.common.exception.ParamsErrorException;
import com.sunedai.tiger.common.utils.OrdNoUtils;
import com.sunedai.tiger.dao.system.DictionaryDao;
import com.sunedai.tiger.dao.system.entity.Dictionary;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;

/**
 * 数据字典服务类
 * @author zhaolipeng
 */
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class DictionaryService {

  @Resource private DictionaryDao dictionaryDao;

  @Transactional(rollbackFor = Exception.class)
  public Dictionary saveOrUpdate(Dictionary dictionary, Long loginUsrId){
    EnumDictType enumDictType = EnumDictType.getEnumDictTypeByType(dictionary.getType());
    if (enumDictType == null){
      throw ParamsErrorException.create("字典类型错误");
    }
    if (StrUtil.isBlank(dictionary.getOrdNo())){
      dictionary.setOrdNo(OrdNoUtils.getOrderNoByType(EnumOrdNoType.ENTITY));
    }
    dictionary.setTypeDescribe(enumDictType.getName());
    dictionary.setOperateUsrId(loginUsrId);
    dictionaryDao.save(dictionary);
    return dictionary;
  }

  public List<Dictionary> listByType(EnumDictType enumDictType){
    return dictionaryDao.findByType(enumDictType.getType());
  }

  public Dictionary findByTypeAndCode(EnumDictType enumDictType, String code){
    if (enumDictType == null){
      throw ParamsErrorException.create("字典类型错误");
    }
    Dictionary dictionary = dictionaryDao.findByTypeAndCode(enumDictType.getType(), code);
    if (dictionary == null) {
      throw ParamsErrorException.create("未找到对应的数据字典");
    }
    return dictionary;
  }

  public List<Dictionary> list(int p, int max) {
    return dictionaryDao.findAll(PageRequest.of(p, max)).getContent();
  }

  public long count(){
    return dictionaryDao.count();
  }
}
